/**
 * 基本方法
 * getDatePattern 时间格式化
 * getDateDiff 根据当前时间判断是多久前
 * accAdd 计算 - 加法
 * accSub 计算 - 减法
 * accMul 计算 - 乘法
 * accDiv 计算 - 除法
 */

/**
 * 时间格式化
 * @param {Date} date 日期
 * @param {String} fmt 格式化方式：要格式的类型 ('yyyy-MM-dd hh:mm:ss')/('yyyy-MM-dd')/('MM-dd')/('yyyy年MM月dd日')/('周E')
 * @return {String} 返回格式化后的日期
 * @注：年、月、日、小时可以任意截取如：('yyyy') 、(hh ：12小时制、HH：24小时制)
 */
export function getDatePattern(date, fmt) {
    let o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
        "H+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),
        "S": date.getMilliseconds()
    };
    let week = {
        "0": "日",
        "1": "一",
        "2": "二",
        "3": "三",
        "4": "四",
        "5": "五",
        "6": "六"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]);
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

/**
 * 根据当前时间判断是多久前
 * @param {Number} dateTimeStamp 传入的毫秒级时间戳
 * @return {String} 返回时间文字描述
 */
export function getDateDiff(dateTimeStamp) {
    let minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
    let hour = minute * 60;
    let day = hour * 24;
    let week = day * 7;
    let month = day * 30;
    let now = new Date().getTime(); //获取当前时间毫秒
    let diffValue = now - dateTimeStamp; //时间差
    if (diffValue < 0) {
        return;
    }
    let minC = parseInt(diffValue / minute); //计算时间差的分，时，天，周，月
    let hourC = parseInt(diffValue / hour);
    let dayC = parseInt(diffValue / day);
    let weekC = parseInt(diffValue / week);
    let monthC = parseInt(diffValue / month);
    let result = "";
    if (monthC >= 1 && monthC <= 3) {
        result = " " + parseInt(monthC) + "月前"
    } else if (weekC >= 1 && weekC <= 3) {
        result = " " + parseInt(weekC) + "周前"
    } else if (dayC >= 1 && dayC <= 6) {
        result = " " + parseInt(dayC) + "天前"
    } else if (hourC >= 1 && hourC <= 23) {
        result = " " + parseInt(hourC) + "小时前"
    } else if (minC >= 1 && minC <= 59) {
        result = " " + parseInt(minC) + "分钟前"
    } else if (diffValue >= 0 && diffValue <= minute) {
        result = "刚刚"
    } else {
        let datetime = new Date();
        datetime.setTime(dateTimeStamp);
        let Nyear = datetime.getFullYear();
        let Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        let Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        let Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        let Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        let Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        result = Nyear + "-" + Nmonth + "-" + Ndate
    }
    return result;
}

/**
 * 聊天截取时间
 * @param {Number} dateTimeStamp 传入的毫秒级时间戳
 * @return {String} 返回时间文字描述
 */
export function getDateChat(dateTimeStamp) {
    let minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
    let hour = minute * 60;
    let day = hour * 24;
    let week = day * 7;
    let month = day * 30;
    let now = new Date().getTime(); //获取当前时间毫秒
    let diffValue = now - dateTimeStamp; //时间差
    if (diffValue < 0) {
        return;
    }
    let minC = parseInt(diffValue / minute); //计算时间差的分，时，天，周，月
    let hourC = parseInt(diffValue / hour);
    let dayC = parseInt(diffValue / day);
    let weekC = parseInt(diffValue / week);
    let monthC = parseInt(diffValue / month);
    let result = "";

    let datetime = new Date();
    datetime.setTime(dateTimeStamp);
    let Nyear = datetime.getFullYear();
    let Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    let Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    let Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
    let Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    let Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    if (dayC >= 1) {
        result = Nyear + "-" + Nmonth + "-" + Ndate
    } else {
        result = Nhour + ":" + Nminute
    }
    return result;
}


/**
 * 判断是否为正确的JSON字符串
 * @param {String} str
 * @return {Boolean}
 */
export function isJSON(str) {
    if (typeof str == 'string') {
        try {
            JSON.parse(str);
            return true
        } catch (e) {
            return false
        }
    } else {
        return false
    }
}

/**
 * 防抖
 * @param {String} fn 方法
 * @param {String} delay 延迟时间
 * @return null
 */
export function onDeb(fn, delay = 300) {
    let timer = null;//借助闭包
    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(fn, delay) // 简化写法
    }
}

/**
 * 节流
 * @param {String} fn 方法
 * @param {String} delay 延迟时间
 * @return null
 */
export function onThro(fn, delay = 300) {
    let valid = true;
    return function () {
        if (!valid) {
            //休息时间 暂不接客
            return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
            fn();
            valid = true;
        }, delay)
    }
}


/**
 * 计算 - 加法
 * @param {String|Number} arg1 数字1
 * @param {String|Number} arg2 数字2
 */
export function accAdd(arg1 = 0, arg2 = 0) {
    var r1, r2, m, c;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
}

/**
 * 计算 - 减法
 * @param {String|Number} arg1 数字1
 * @param {String|Number} arg2 数字2
 */
export function accSub(arg1 = 0, arg2 = 0) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

/**
 * 计算 - 乘法
 * @param {String|Number} arg1 数字1
 * @param {String|Number} arg2 数字2
 */
export function accMul(arg1 = 0, arg2 = 0) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

/**
 * 计算 - 除法
 * @param {String|Number} arg1 数字1
 * @param {String|Number} arg2 数字2
 */
export function accDiv(arg1 = 0, arg2) {
    if (!arg2) {
        return
    }
    let t1 = 0, t2 = 0, r1, r2;
    try {
        t1 = arg1.toString().split(".")[1].length
    } catch (e) {
    }
    try {
        t2 = arg2.toString().split(".")[1].length
    } catch (e) {
    }
    r1 = Number(arg1.toString().replace(".", ""))
    r2 = Number(arg2.toString().replace(".", ""))
    return (r1 / r2) * Math.pow(10, t2 - t1);
}